package tech.xiaozai.rbac.exce;

import org.springframework.security.access.AccessDeniedException;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import tech.xiaozai.common.exception.BusinessException;
import tech.xiaozai.common.restful.RestResp;
import tech.xiaozai.common.restful.Error;

import javax.servlet.http.HttpServletResponse;

/**
 * @author xiaozai
 * @version 1.0
 * @date 2020-09-15 21:14
 *
 *  统一异常处理器
 */

@ControllerAdvice
public class CommonExceptionHandler {

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public RestResp handleException(Exception e, HttpServletResponse response) throws Exception {

        System.out.println("e="+e.getClass().getName());
        e.printStackTrace();

        // TODO  所有异常信息应该写入服务器文件日志中
        if(e instanceof BindException){
            response.setStatus(400);
            return RestResp.error(Error.ILLEGAL_ARGUMENT_ERROR);
        }

        // TODO  以后要有新的异常，需要在此处集中处理
        if( e instanceof BusinessException){
            response.setStatus(400);
            return RestResp.error(Error.BUSINESS_ERROR);
        }

        //spring security方法拦截抛的异常, 因为是权限不够，
        // 此异常是由security的方法拦截器抛出，理应交给security的异常翻译器去处理
        // 所以继承往外抛
        if ( e instanceof AccessDeniedException){
            throw e;
        }

        response.setStatus(400);
        //其它未知异常都返回这个错误信息
        return RestResp.error(Error.UNKNOWN_ERROR);
    }
}
